package monkey;

import java.util.concurrent.CountDownLatch;

public class Test3 {

    private static final Object locker = new Object();

    public static void main(String[] args) throws InterruptedException {
        // 初始化 100 颗桃子
        CountDownLatch count = new CountDownLatch(100);

        // 收集最终结果
        int[] res = new int[3];

        // 三子猴子去争抢
        for (int i = 0; i < 3; i++) {
            int index = i;
            Thread t = new Thread(() -> {
                while (count.getCount() > 0) {
                    synchronized (locker) {
                        if (count.getCount() > 0) {
                            res[index]++;
                            count.countDown();
                        }
                    }
                }
            });
            t.start();
        }

        // 阻塞到桃子吃完
        count.await();

        for (int i = 0; i < 3; i++) {
            System.out.println("第 " + (i + 1) + " 只猴子吃了 " + res[i] + " 个桃子。");
        }

    }
}
